import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware } from '@/utils/auth';
import { join } from 'path';
import { writeFile, mkdir } from 'fs/promises';
import { existsSync } from 'fs';

// 定义允许的文件类型
const ALLOWED_FILE_TYPES = [
  'application/pdf',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
];

// 最大文件大小 (5MB)
const MAX_FILE_SIZE = 5 * 1024 * 1024;

// 简历存储路径
const UPLOAD_DIR = join(process.cwd(), 'public', 'uploads', 'resumes');

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      // 如果返回的是NextResponse，说明验证失败
      return authResult;
    }

    const userId = authResult.id;

    // 确保上传目录存在
    if (!existsSync(UPLOAD_DIR)) {
      await mkdir(UPLOAD_DIR, { recursive: true });
    }

    // 创建个人目录
    const userUploadDir = join(UPLOAD_DIR, userId.toString());
    if (!existsSync(userUploadDir)) {
      await mkdir(userUploadDir, { recursive: true });
    }

    // 处理文件上传
    const formData = await request.formData();
    const file = formData.get('file') as File;

    if (!file) {
      return NextResponse.json(
        { error: '未找到文件' },
        { status: 400 }
      );
    }

    // 验证文件类型
    if (!ALLOWED_FILE_TYPES.includes(file.type)) {
      return NextResponse.json(
        { error: '不支持的文件类型，仅支持PDF和DOCX格式' },
        { status: 400 }
      );
    }

    // 验证文件大小
    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { error: '文件太大，最大允许5MB' },
        { status: 400 }
      );
    }

    // 获取文件扩展名
    const fileExt = file.name.split('.').pop() || '';

    // 创建唯一的文件名
    const timestamp = new Date().getTime();
    const fileName = `resume_${userId}_${timestamp}.${fileExt}`;
    const filePath = join(userUploadDir, fileName);

    // 将文件内容转换为Buffer并写入文件系统
    const fileBuffer = await file.arrayBuffer();
    await writeFile(filePath, Buffer.from(fileBuffer));

    // 构建文件URL (相对于public目录)
    const fileUrl = `/uploads/resumes/${userId}/${fileName}`;

    return NextResponse.json({
      success: true,
      url: fileUrl,
      fileName: fileName
    });
  } catch (error) {
    console.error('File upload error:', error);
    return NextResponse.json(
      { error: '文件上传失败' },
      { status: 500 }
    );
  }
}